import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import "./App.css";

function App() {
   const [count, setCount] = useState(0)

   const updateCount = () => {
    setCount(count + 1)
   }

   function useInterval (fn, delay) {
        const callbackFn = useRef(fn)

        useLayoutEffect(() => {
            callbackFn.current = fn
        })

        const cleanUpFnRef = useRef()
        // 该函数不会发生变化，所以用useCallback进行包裹
        const clean = useCallback(() => {
            cleanUpFnRef.current?.()
        }, [])

        useEffect(() => {
            const timer = setInterval(() => callbackFn.current(), delay)
            cleanUpFnRef.current = () => {
                clearInterval(timer)
            }
            return clean
        }, [])
        // clean函数作为参数返回，在外部也能够引用的到
        return clean
   }

   useInterval(updateCount, 1000)

   return <>
    <div>{count}</div>
   </>
}

export default App;
